import { useState, useEffect } from 'react';
import { useParams, useLocation, useNavigate } from 'react-router-dom';
import { ArrowLeft, MessageCircle, Heart, Plus, Star } from 'lucide-react';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { 
  followDoctor, 
  unfollowDoctor, 
  addFollowedDoctor,
  fetchReviewTags,
  fetchReviews,
  fetchBanners,
  submitReview,
  sendBanner,
  updateReviewReplies,
  type Review
} from '../store/doctorSlice';
import { fetchDoctorDetail } from '../store/doctorDetailSlice';
import { addConsultationRecord } from '../utils/consultationUtils';

type ReviewFormData = { name: string; title: string; rating: number; tags: string[] };

type ReviewFormProps = {
  reviewTags: Array<{classifyid: string; classifytitle: string}>;
  onSubmit: (data: ReviewFormData) => void;
  onCancel: () => void;
};

type BannerFormProps = {
  banners: { state?: string; image?: string }[];
  onSubmit: (data: { name: string; image: string; state: string; timer: string }) => void;
  onCancel: () => void;
};

interface DoctorData {
  doctorName: string;
  doctorDescription: string;
}

/**
 * 医生详情页面组件
 * 
 * 功能特性：
 * - 医生基本信息展示
 * - 关注/取消关注医生
 * - 评论和锦旗功能
 * - 在线咨询入口
 * - Redux状态管理集成
 * - 评论提交后自动记录到问诊记录
 * 
 * 主要状态：
 * - doctor: 医生详细信息
 * - loading: 页面加载状态
 * - showReviewModal: 评论模态框显示状态
 * - showBannerModal: 锦旗模态框显示状态
 * - showReplyModal: 回复模态框显示状态
 * 
 * 路由参数：
 * - doctorId: 医生ID（从URL参数获取）
 * 
 * 状态传递：
 * - doctorData: 从路由state获取的医生数据
 * 
 * @returns {JSX.Element} 医生详情页面组件
 */
export default function DoctorDetailPage() {
  const { doctorId } = useParams<{ doctorId: string }>();
  const location = useLocation();
  const navigate = useNavigate();
  const doctorData = location.state as DoctorData;
  
  console.log('DoctorDetailPage 渲染:', {
    doctorId,
    doctorData,
    location: location.pathname
  });
  
  // Redux hooks
  const dispatch = useAppDispatch();
  const { 
    followedDoctors, 
    loading: followLoading, 
    error,
    reviews,
    banners,
    reviewTags
  } = useAppSelector(state => state.doctor);
  const { 
    currentDoctor,
    loading: doctorDetailLoading
  } = useAppSelector(state => state.doctorDetail);
  const userInfo = useAppSelector(state => state.user.userInfo);
  const currentNickname = userInfo?.name || (userInfo?.phone ? `用户${String(userInfo.phone).slice(-4)}` : '游客');
  
  const [doctor, setDoctor] = useState({
    name: doctorData?.doctorName || currentDoctor?.name || '未知医生',
    title: currentDoctor?.title || '医生',
    specialty: currentDoctor?.specialties || '',
    hospital: currentDoctor?.hospital || '未知医院',
    avatar: currentDoctor?.avatar || '',
    isOnline: currentDoctor?.isOnline || false,
    views: currentDoctor?.views || 0,
    rating: currentDoctor?.rating || 0,
    responseTime: '',
    followers: 0,
    expertise: doctorData?.doctorDescription || currentDoctor?.specialties || '',
    reviews: reviews.length
  });
  
  const [loading, setLoading] = useState(true);
  // 使用Redux的loading状态
  const isLoading = loading || doctorDetailLoading;

  // 监听currentDoctor变化，更新本地doctor状态
  useEffect(() => {
    if (currentDoctor) {
      setDoctor(prev => ({
        ...prev,
        name: currentDoctor.name || prev.name,
        title: currentDoctor.title || prev.title,
        specialty: currentDoctor.specialties || prev.specialty,
        hospital: currentDoctor.hospital || prev.hospital,
        avatar: currentDoctor.avatar || prev.avatar,
        isOnline: currentDoctor.isOnline || prev.isOnline,
        views: currentDoctor.views || prev.views,
        rating: currentDoctor.rating || prev.rating,
        expertise: currentDoctor.specialties || prev.expertise,
        reviews: reviews.length
      }));
      setLoading(false);
    }
  }, [currentDoctor, reviews.length]);
  
  // 模态框状态
  const [showReviewModal, setShowReviewModal] = useState(false);
  const [showBannerModal, setShowBannerModal] = useState(false);
  // 回复相关
  const [showReplyModal, setShowReplyModal] = useState(false);
  const [replyContent, setReplyContent] = useState('');
  const [currentReview, setCurrentReview] = useState<Review | null>(null); // 用于存储当前回复的评价

  const handleBack = () => {
    navigate(-1);
  };

  const handleFollow = () => {
    if (!doctorId) return;
    
    const isFollowed = followedDoctors.includes(doctorId);
    
    if (isFollowed) {
      // 取消关注
      dispatch(unfollowDoctor({ id: doctorId, doctorflag: '0' }));
    } else {
      // 关注医生 - 先添加到本地store，再调用API
      const doctorData = {
        id: doctorId,
        name: doctor.name,
        title: doctor.title,
        hospital: doctor.hospital,
        department: doctor.specialty,
        avatar: doctor.avatar,
        isOnline: doctor.isOnline,
        consultationMethods: ['图文咨询'],
        specialties: doctor.expertise,
        rating: doctor.rating,
        commendations: Math.floor(Math.random() * 10),
        views: doctor.views,
        price: Math.floor(Math.random() * 50) + 10,
        isGradeA: Math.random() > 0.7
      };
      
      // 先添加到本地store
      dispatch(addFollowedDoctor(doctorData));
      
      // 再调用API
      dispatch(followDoctor({ id: doctorId, doctorflag: '1' }));
    }
  };

  const handleSendMessage = () => {
    // 跳转到医生咨询页面
    if (doctorId) {
      navigate(`/consultation/${doctorId}`);
    }
  };

  // 处理评论提交
  const handleSubmitReview = async (reviewData: ReviewFormData) => {
    if (!doctorId) return;
    
    try {
      await dispatch(submitReview({ reviewData, doctorId })).unwrap();
      
      // 评论成功后，将医生记录到问诊记录中
      const doctorInfo = {
        id: doctorId,
        name: doctor.name,
        avatar: doctor.avatar,
        department: doctor.specialty,
        hospital: doctor.hospital,
        consultationMethods: ['图文咨询']
      };
      
      // 添加问诊记录，包含用户评论
      const comment = `${reviewData.title}: ${reviewData.tags.join(', ')}`;
      addConsultationRecord(doctorInfo, comment);
      
      setShowReviewModal(false);
      alert('评论提交成功！医生已添加到您的问诊记录中。\n\n注意：新评论已添加到本地显示，如需同步服务器数据请点击"刷新"按钮。');
    } catch {
      // console.error('提交评论失败:', error);
      alert('评论提交失败，请检查网络连接');
    }
  };

  // 赠送锦旗提交
  const handleSendBanner = async (data: { name: string; image: string; state: string; timer: string }) => {
    if (!doctorId) return;
    try {
      await dispatch(sendBanner({ bannerData: data, doctorId })).unwrap();
      setShowBannerModal(false);
      alert('锦旗赠送成功！');
    } catch {
      // console.error('赠送锦旗失败:', e);
      alert('赠送锦旗失败，请稍后重试');
    }
  };

  // 回复提交
  const handleSubmitReply = async () => {
    if (!doctorId) return;
    if (!replyContent.trim()) {
      alert('请输入回复内容');
      return;
    }
    if (!currentReview) {
      alert('请选择一个评价进行回复');
      return;
    }
    
    try {
      // 创建回复数据
      const newReply = {
        replierName: currentNickname,
        content: replyContent.trim(),
        timer: new Date().toISOString().split('T')[0]
      };
      
      // 找到当前评价在数组中的索引
      const reviewIndex = reviews.findIndex(review => review === currentReview);
      if (reviewIndex !== -1) {
        // 通过 Redux 立即更新评论状态，让回复内容立即显示
        dispatch(updateReviewReplies({
          reviewIndex,
          reply: newReply
        }));
      }
      
      // console.log('回复已添加:', newReply);
      
      setShowReplyModal(false);
      setReplyContent('');
      setCurrentReview(null);
      alert('回复已提交！');
      
      // 注意：这里不刷新数据，让用户能看到刚回复的内容
      // 如果需要持久化到服务器，可以在这里调用 API
      // await handleRefreshReviews();
    } catch {
      // console.error('回复失败:', e);
      alert('回复失败，请稍后重试');
    }
  };

  // 刷新评论数据
  const handleRefreshReviews = async () => {
    if (!doctorId) return;
    try {
      await dispatch(fetchReviews(doctorId)).unwrap();
      alert('评论数据已刷新');
    } catch {
      // console.error('刷新评论失败:', error);
      alert('刷新评论失败');
    }
  };

  // 刷新锦旗数据
  const handleRefreshBanners = async () => {
    try {
      await dispatch(fetchBanners()).unwrap();
      alert('锦旗数据已刷新');
    } catch {
      // console.error('刷新锦旗失败:', error);
      alert('刷新锦旗失败');
    }
  };

  // 通过 Redux 获取医生详情数据
  useEffect(() => {
    if (!doctorId) return;
    
    // 使用Redux获取医生详情
    dispatch(fetchDoctorDetail(doctorId));
  }, [doctorId, dispatch]);

  // 获取评论、锦旗和标签数据（仅当本地无数据时才请求，避免覆盖持久化数据）
  useEffect(() => {
    if (!doctorId) return;

    if (!reviewTags || reviewTags.length === 0) {
      dispatch(fetchReviewTags());
    }
    if (!reviews || reviews.length === 0) {
      dispatch(fetchReviews(doctorId));
    }
    if (!banners || banners.length === 0) {
      dispatch(fetchBanners());
    }
  }, [doctorId, dispatch, reviewTags.length, reviews.length, banners.length]);

  // 如果正在加载，显示加载状态
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">正在加载医生信息...</p>
        </div>
      </div>
    );
  }

  // 如果没有医生数据，显示错误状态
  if (!doctor.name || doctor.name === '未知医生') {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-red-500 text-6xl mb-4">⚠️</div>
          <p className="text-gray-600 mb-4">未找到医生信息</p>
          <p className="text-sm text-gray-500 mb-4">医生ID: {doctorId}</p>
          <p className="text-sm text-gray-500 mb-4">路由状态: {JSON.stringify(doctorData)}</p>
          <p className="text-sm text-gray-500 mb-4">Redux状态: {currentDoctor ? '有数据' : '无数据'}</p>
          <button
            onClick={handleBack}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            返回上一页
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 头部 */}
      <div className="bg-white shadow-sm">
        <div className="flex items-center px-4 py-3">
          <button
            onClick={handleBack}
            className="mr-3 p-2 hover:bg-gray-100 rounded-full transition-colors"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-gray-900">医生详情</h1>
        </div>
      </div>

      {/* 医生头部信息 */}
      <div className="bg-white p-4 border-b border-gray-100">
        <div className="flex items-start space-x-4">
          {/* 头像 */}
          <div className="relative">
            {doctor.avatar && doctor.avatar.startsWith('http') ? (
              <img 
                src={doctor.avatar} 
                alt={doctor.name}
                className="w-20 h-20 rounded-full object-cover"
                onError={(e) => {
                  // 如果图片加载失败，隐藏图片元素，显示字母头像
                  const target = e.target as HTMLImageElement;
                  target.style.display = 'none';
                  const parent = target.parentElement;
                  if (parent) {
                    const fallback = parent.querySelector('.avatar-fallback') as HTMLElement;
                    if (fallback) fallback.style.display = 'flex';
                  }
                }}
              />
            ) : null}
            <div className={`w-20 h-20 rounded-full bg-blue-100 flex items-center justify-center avatar-fallback ${doctor.avatar && doctor.avatar.startsWith('http') ? 'hidden' : ''}`}>
              <span className="text-2xl font-semibold text-blue-600">
                {doctor.avatar && !doctor.avatar.startsWith('http') ? doctor.avatar : (doctor.name || '').charAt(0)}
              </span>
            </div>
            {doctor.isOnline && (
              <div className="absolute -bottom-1 -right-1">
                <div className="w-5 h-5 bg-green-500 rounded-full border-2 border-white"></div>
              </div>
            )}
          </div>
          
          {/* 医生信息 */}
          <div className="flex-1">
            <div className="flex items-center justify-between mb-2">
              <h2 className="text-xl font-bold text-gray-900">
                {doctor.name}
              </h2>
              <button
                onClick={handleFollow}
                disabled={followLoading}
                className={`px-3 py-1 text-sm rounded-full flex items-center space-x-1 transition-colors ${
                  followedDoctors.includes(doctorId || '')
                    ? 'bg-gray-500 text-white hover:bg-gray-600'
                    : 'bg-red-500 text-white hover:bg-red-600'
                } ${followLoading ? 'opacity-50 cursor-not-allowed' : ''}`}
              >
                {followLoading ? (
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                ) : followedDoctors.includes(doctorId || '') ? (
                  <Heart size={14} fill="white" />
                ) : (
                  <Plus size={14} />
                )}
                <span>
                  {followLoading 
                    ? '处理中...' 
                    : followedDoctors.includes(doctorId || '') 
                      ? '已关注' 
                      : '关注'
                  }
                </span>
              </button>
            </div>
            
            <div className="flex items-center space-x-2 mb-2">
              <span className="text-gray-600">{doctor.title}</span>
              <span className="text-gray-400">|</span>
              <span className="text-gray-600">{doctor.specialty}</span>
            </div>
            
            <p className="text-sm text-gray-500 leading-relaxed">
              {doctor.hospital}
            </p>
          </div>
        </div>
      </div>

      {/* 统计数据 */}
      <div className="bg-white p-4 border-b border-gray-100">
        <div className="grid grid-cols-4 gap-4">
          <div className="text-center">
            <div className="text-lg font-bold text-gray-900">{doctor.views.toLocaleString()}</div>
            <div className="text-xs text-gray-500">浏览人次</div>
          </div>
          <div className="text-center">
            <div className="text-lg font-bold text-gray-900">{doctor.rating}%</div>
            <div className="text-xs text-gray-500">好评率</div>
          </div>
          <div className="text-center">
            <div className="text-lg font-bold text-gray-900">{doctor.responseTime}</div>
            <div className="text-xs text-gray-500">平均响应</div>
          </div>
          <div className="text-center">
            <div className="text-lg font-bold text-gray-900">{doctor.followers.toLocaleString()}</div>
            <div className="text-xs text-gray-500">粉丝数</div>
          </div>
        </div>
      </div>

      {/* 擅长领域 */}
      <div className="bg-white p-4 border-b border-gray-100">
        <div className="mb-3">
          <h3 className="text-base font-semibold text-gray-900">擅长:</h3>
        </div>
        <p className="text-sm text-gray-600 leading-relaxed mb-2">
          {doctor.expertise}
        </p>
        <button className="text-blue-600 text-sm hover:text-blue-700">
          查看简介&gt;
        </button>
      </div>

      {/* 关注状态错误提示 */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-3 mx-4 mb-4">
          <div className="flex items-center space-x-2">
            <div className="w-4 h-4 bg-red-500 rounded-full flex items-center justify-center">
              <span className="text-white text-xs">!</span>
            </div>
            <span className="text-red-700 text-sm">{error}</span>
            <button
              onClick={() => dispatch({ type: 'doctor/clearError' })}
              className="ml-auto text-red-500 hover:text-red-700"
            >
              ✕
            </button>
          </div>
        </div>
      )}

      {/* 医生服务 */}
      <div className="bg-white p-4 border-b border-gray-100">
        <h3 className="text-base font-semibold text-gray-900 mb-4">医生服务</h3>
        <div className="grid grid-cols-4 gap-4">
          <div className="text-center">
            <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-2">
              <MessageCircle className="text-blue-600" size={24} />
            </div>
            <div className="text-xs text-gray-900">在线咨询</div>
            <div className="text-xs text-gray-500">1对1问医生</div>
          </div>
          
          <div className="text-center">
            <div className="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-2">
              <span className="text-purple-600 font-bold text-lg">Rx</span>
            </div>
            <div className="text-xs text-gray-900">复诊开方</div>
            <div className="text-xs text-gray-500">申请用药</div>
          </div>
          
          <div className="text-center">
            <div className="w-12 h-12 bg-orange-100 rounded-full flex items-center justify-center mx-auto mb-2">
              <div className="flex items-center space-x-1">
                <span className="text-orange-600">👍</span>
                <span className="text-orange-600">⭐</span>
              </div>
            </div>
            <div className="text-xs text-gray-900">优选药房</div>
            <div className="text-xs text-gray-500">用心优选</div>
          </div>
          
          <div className="text-center">
            <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-2">
              <span className="text-gray-400">🏥</span>
            </div>
            <div className="text-xs text-gray-900">门诊预约</div>
            <div className="text-xs text-gray-500">未开通</div>
          </div>
        </div>
      </div>

      {/* 患者评价 */}
      <div className="bg-white p-4 border-b border-gray-100">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-base font-semibold text-gray-900">评价 ({reviews.length})</h3>
          <div className="flex items-center space-x-2">
            <button 
              onClick={() => setShowReviewModal(true)}
              className="text-blue-600 text-sm hover:text-blue-700"
            >
              写评价
            </button>
            <button 
              onClick={handleRefreshReviews}
              className="text-gray-600 text-sm hover:text-gray-700"
            >
              刷新&gt;
            </button>
            <button className="text-blue-600 text-sm hover:text-blue-700">
              查看更多&gt;
            </button>
          </div>
        </div>
        
        <div className="space-y-4">
          {reviews.length > 0 ? (
            reviews.slice(0, 5).map((review, index) => (
              <div key={index} className="space-y-3">
                {/* 主评价 */}
                <div className="flex items-start space-x-3 p-4 bg-gray-50 rounded-lg border-l-4 border-blue-500">
                  {review.avatar && review.avatar.startsWith('http') ? (
                    <img 
                      src={review.avatar} 
                      alt={review.name}
                      className="w-10 h-10 rounded-full object-cover flex-shrink-0"
                      onError={(e) => {
                        const target = e.target as HTMLImageElement;
                        target.style.display = 'none';
                        const parent = target.parentElement;
                        if (parent) {
                          const fallback = parent.querySelector('.review-avatar-fallback') as HTMLElement;
                          if (fallback) fallback.style.display = 'flex';
                        }
                      }}
                    />
                  ) : null}
                  <div className={`w-10 h-10 bg-gradient-to-br from-blue-100 to-blue-200 rounded-full flex items-center justify-center flex-shrink-0 review-avatar-fallback ${review.avatar && review.avatar.startsWith('http') ? 'hidden' : ''}`}>
                    <span className="text-sm font-medium text-blue-700">
                      {review.name ? review.name.charAt(0) : '用'}
                    </span>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-2 mb-2">
                      <span className="text-sm font-medium text-gray-900">
                        {review.name || '匿名用户'}
                      </span>
                      <div className="flex items-center">
                        {[1, 2, 3, 4, 5].map((star) => (
                          <Star
                            key={star}
                            size={14}
                            className={`${star <= (review.good || 5) ? 'text-yellow-400 fill-current' : 'text-gray-300'}`}
                          />
                        ))}
                      </div>
                      <span className="text-xs text-gray-500">
                        {review.timer || new Date().toISOString().split('T')[0]}
                      </span>
                      <button
                        className="ml-auto text-xs text-blue-600 hover:text-blue-700 bg-blue-50 px-2 py-1 rounded hover:bg-blue-100 transition-colors"
                        onClick={() => {
                          setShowReplyModal(true);
                          setCurrentReview(review);
                        }}
                      >
                        回复
                      </button>
                    </div>
                    
                    {review.state && (
                      <div className="flex flex-wrap gap-1 mb-3">
                        {Array.isArray(review.state) ? review.state.map((tag, tagIndex) => (
                          <span key={tagIndex} className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">
                            {tag}
                          </span>
                        )) : (
                          <span className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">
                            {review.state}
                          </span>
                        )}
                      </div>
                    )}
                    
                    <p className="text-sm text-gray-700 leading-relaxed">
                      {review.title || '感谢医生的专业服务'}
                    </p>
                  </div>
                </div>
                
                {/* 回复内容 */}
                {review.replies && review.replies.length > 0 && (
                  <div className="ml-8 space-y-2">
                    {review.replies.map((reply, replyIndex) => (
                      <div key={replyIndex} className="flex items-start space-x-3 p-3 bg-white rounded-lg border border-gray-200">
                        {reply.avatar && reply.avatar.startsWith('http') ? (
                          <img 
                            src={reply.avatar} 
                            alt={reply.replierName}
                            className="w-8 h-8 rounded-full object-cover flex-shrink-0"
                            onError={(e) => {
                              const target = e.target as HTMLImageElement;
                              target.style.display = 'none';
                              const parent = target.parentElement;
                              if (parent) {
                                const fallback = parent.querySelector('.reply-avatar-fallback') as HTMLElement;
                                if (fallback) fallback.style.display = 'flex';
                              }
                            }}
                          />
                        ) : null}
                        <div className={`w-8 h-8 bg-gradient-to-br from-green-100 to-green-200 rounded-full flex items-center justify-center flex-shrink-0 reply-avatar-fallback ${reply.avatar && reply.avatar.startsWith('http') ? 'hidden' : ''}`}>
                          <span className="text-xs font-medium text-green-700">
                            {reply.replierName ? reply.replierName.charAt(0) : '回'}
                          </span>
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center space-x-2 mb-1">
                            <span className="text-sm font-medium text-gray-900">
                              {reply.replierName || '医生回复'}
                            </span>
                            <span className="text-xs text-gray-500">
                              {reply.timer || new Date().toISOString().split('T')[0]}
                            </span>
                          </div>
                          <p className="text-sm text-gray-700">
                            {reply.content}
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ))
          ) : (
            <div className="text-center py-8 text-gray-500">
              <div className="w-16 h-16 mx-auto mb-3 bg-gray-100 rounded-full flex items-center justify-center">
                <span className="text-2xl">💬</span>
              </div>
              <p>暂无评价</p>
              <p className="text-sm mt-1">成为第一个评价的人吧！</p>
            </div>
          )}
        </div>
      </div>

      {/* 锦旗 */}
      <div className="bg-white p-4 border-b border-gray-100">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-base font-semibold text-gray-900">
            锦旗 ({banners.length})
            {banners.length > 0 && (
              <span className="text-sm text-gray-500 ml-2">
                (显示前3个)
              </span>
            )}
          </h3>
          <div className="flex items-center space-x-2">
            <button 
              onClick={() => setShowBannerModal(true)}
              className="text-blue-600 text-sm hover:text-blue-700"
            >
              我要送锦旗&gt;
            </button>
            <button 
              onClick={handleRefreshBanners}
              className="text-gray-600 text-sm hover:text-gray-700"
            >
              刷新&gt;
            </button>
            <button className="text-blue-600 text-sm hover:text-blue-700">
              查看更多&gt;
            </button>
          </div>
        </div>
        
        <div className="grid grid-cols-3 gap-3">
          {banners.length > 0 ? (
            banners.slice(0, 3).map((banner, index) => (
              <div key={index} className="text-center">
                <div className="w-16 h-16 mx-auto mb-2 bg-red-100 rounded-lg flex items-center justify-center">
                  <span className="text-2xl">🎁</span>
                </div>
                <p className="text-xs text-gray-700">{banner.state || '医术精湛'}</p>
                {banner.name && (
                  <p className="text-xs text-gray-500 mt-1">来自: {banner.name}</p>
                )}
              </div>
            ))
          ) : (
            <div className="col-span-3 text-center py-4 text-gray-500">
              暂无锦旗
            </div>
          )}
        </div>
      </div>

      {/* 底部发消息按钮 */}
      <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 safe-area-bottom">
        <button
          onClick={handleSendMessage}
          className="w-full bg-blue-600 text-white py-3 rounded-lg font-medium hover:bg-blue-700 transition-colors"
        >
          发消息
        </button>
      </div>
      
      {/* 底部占位，防止内容被按钮遮挡 */}
      <div className="h-20"></div>

      {/* 评论模态框 */}
      {showReviewModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-11/12 max-w-md">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">写评价</h3>
              <button
                onClick={() => setShowReviewModal(false)}
                className="text-gray-500 hover:text-gray-700"
              >
                ✕
              </button>
            </div>
            
            <ReviewForm 
              reviewTags={reviewTags}
              onSubmit={handleSubmitReview}
              onCancel={() => setShowReviewModal(false)}
            />
          </div>
        </div>
      )}

      {/* 回复模态框 */}
      {showReplyModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-11/12 max-w-md">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">回复评论</h3>
              <button
                onClick={() => {
                  setShowReplyModal(false);
                  setCurrentReview(null);
                  setReplyContent('');
                }}
                className="text-gray-500 hover:text-gray-700"
              >
                ✕
              </button>
            </div>
            
            {/* 显示回复目标 */}
            {currentReview && (
              <div className="mb-4 p-3 bg-gray-50 rounded-lg border-l-4 border-blue-500">
                <div className="flex items-center space-x-2 mb-2">
                  <div className="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">
                    <span className="text-xs text-blue-700">
                      {currentReview.name ? currentReview.name.charAt(0) : '用'}
                    </span>
                  </div>
                  <span className="text-sm font-medium text-gray-900">
                    {currentReview.name || '匿名用户'}
                  </span>
                  <span className="text-xs text-gray-500">
                    {currentReview.timer || '刚刚'}
                  </span>
                </div>
                <p className="text-sm text-gray-700">
                  {currentReview.title || '感谢医生的专业服务'}
                </p>
              </div>
            )}
            
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium mb-2">回复内容</label>
                <textarea
                  value={replyContent}
                  onChange={(e) => setReplyContent(e.target.value)}
                  rows={4}
                  placeholder="请输入您的回复内容..."
                  className="w-full p-3 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  maxLength={200}
                />
                <div className="text-right text-xs text-gray-500 mt-1">
                  {replyContent.length}/200
                </div>
              </div>
              
              <div className="flex space-x-3">
                <button
                  onClick={() => {
                    setShowReplyModal(false);
                    setCurrentReview(null);
                    setReplyContent('');
                  }}
                  className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleSubmitReply}
                  disabled={!replyContent.trim()}
                  className="flex-1 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
                >
                  提交回复
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 锦旗模态框 */}
      {showBannerModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-11/12 max-w-md">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">答谢医生</h3>
              <button
                onClick={() => setShowBannerModal(false)}
                className="text-gray-500 hover:text-gray-700"
              >
                ✕
              </button>
            </div>
            
            <BannerForm 
              banners={banners}
              onSubmit={handleSendBanner}
              onCancel={() => setShowBannerModal(false)}
            />
          </div>
        </div>
      )}
    </div>
  );
}

// 评论表单组件
function ReviewForm({ reviewTags, onSubmit, onCancel }: ReviewFormProps) {
  const [formData, setFormData] = useState({
    name: '',
    title: '',
    rating: 5,
    tags: [] as string[]
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(formData);
  };

  const toggleTag = (tag: string) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags.includes(tag) 
        ? prev.tags.filter(t => t !== tag)
        : [...prev.tags, tag]
    }));
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-2">昵称</label>
        <input
          type="text"
          value={formData.name}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => setFormData(prev => ({ ...prev, name: e.target.value }))}
          className="w-full p-2 border border-gray-300 rounded"
          placeholder="请输入您的昵称"
        />
      </div>
      
      <div>
        <label className="block text-sm font-medium mb-2">评价内容</label>
        <textarea
          value={formData.title}
          onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setFormData(prev => ({ ...prev, title: e.target.value }))}
          className="w-full p-2 border border-gray-300 rounded"
          rows={3}
          placeholder="请输入您的评价"
        />
      </div>
      
      <div>
        <label className="block text-sm font-medium mb-2">评分</label>
        <div className="flex items-center space-x-1">
          {[1, 2, 3, 4, 5].map((star) => (
            <button
              key={star}
              type="button"
              onClick={() => setFormData(prev => ({ ...prev, rating: star }))}
              className="focus:outline-none"
            >
              <Star
                size={20}
                className={`${star <= formData.rating ? 'text-yellow-400 fill-current' : 'text-gray-300'}`}
              />
            </button>
          ))}
        </div>
      </div>
      
      {reviewTags.length > 0 && (
        <div>
          <label className="block text-sm font-medium mb-2">标签</label>
          <div className="flex flex-wrap gap-2">
            {reviewTags.map((tag, index) => (
              <button
                key={index}
                type="button"
                onClick={() => toggleTag(tag.classifytitle)}
                className={`px-3 py-1 rounded-full text-sm ${
                  formData.tags.includes(tag.classifytitle)
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-100 text-gray-700'
                }`}
              >
                {tag.classifytitle}
              </button>
            ))}
          </div>
        </div>
      )}
      
      <div className="flex space-x-3">
        <button
          type="button"
          onClick={onCancel}
          className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50"
        >
          取消
        </button>
        <button
          type="submit"
          className="flex-1 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
        >
          提交评价
        </button>
      </div>
    </form>
  );
}

// 锦旗表单组件
function BannerForm({ banners, onSubmit, onCancel }: BannerFormProps) {
  const [formData, setFormData] = useState({
    name: '', // 清空默认昵称
    selectedBanner: banners[0] || null
  });

  // 扩展锦旗种类
  const extendedBanners = [
    ...banners,
    { state: '药到病除', image: 'http://example.com/banner7.jpg' },
    { state: '国医圣手', image: 'http://example.com/banner8.jpg' },
    { state: '杏林春暖', image: 'http://example.com/banner9.jpg' },
    { state: '济世救人', image: 'http://example.com/banner10.jpg' },
    { state: '医者仁心', image: 'http://example.com/banner11.jpg' },
    { state: '妙手仁心', image: 'http://example.com/banner12.jpg' }
  ];

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.selectedBanner) {
      alert('请选择一个锦旗');
      return;
    }
    
    if (!formData.name.trim()) {
      alert('请输入您的昵称');
      return;
    }
    
    const bannerData = {
      name: formData.name.trim(),
      image: formData.selectedBanner.image || 'http://example.com/banner.jpg',
      state: formData.selectedBanner.state || '医术精湛',
      timer: new Date().toISOString().split('T')[0]
    };
    
    // console.log('准备发送锦旗数据:', bannerData);
    onSubmit(bannerData);
    
    // 重置表单状态
    setFormData({
      name: '',
      selectedBanner: extendedBanners[0] || null
    });
  };

  const handleCancel = () => {
    // 重置表单状态
    setFormData({
      name: '',
      selectedBanner: extendedBanners[0] || null
    });
    onCancel();
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-2">选择锦旗</label>
        <div className="grid grid-cols-3 gap-3 max-h-48 overflow-y-auto">
          {extendedBanners.map((banner, index) => (
            <button
              key={index}
              type="button"
              onClick={() => setFormData(prev => ({ ...prev, selectedBanner: banner }))}
              className={`relative p-3 border rounded-lg transition-all duration-200 ${
                formData.selectedBanner === banner
                  ? 'border-blue-500 bg-blue-50 shadow-md scale-105'
                  : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
              }`}
            >
              <div className="w-12 h-12 mx-auto mb-2 bg-gradient-to-br from-red-100 to-yellow-100 rounded-full flex items-center justify-center shadow-sm">
                <span className="text-2xl">🎁</span>
              </div>
              <p className="text-xs text-gray-700 font-medium">{banner.state || '医术精湛'}</p>
              {formData.selectedBanner === banner && (
                <div className="absolute top-1 right-1 w-4 h-4 bg-blue-500 rounded-full flex items-center justify-center">
                  <span className="text-white text-xs">✓</span>
                </div>
              )}
            </button>
          ))}
        </div>
      </div>
      
      <div>
        <label className="block text-sm font-medium mb-2">您的昵称</label>
        <input
          type="text"
          value={formData.name}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => setFormData(prev => ({ ...prev, name: e.target.value }))}
          className="w-full p-2 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          placeholder="请输入您的昵称"
          maxLength={20}
        />
      </div>
      
      <div className="flex space-x-3">
        <button
          type="button"
          onClick={handleCancel}
          className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50 transition-colors"
        >
          取消
        </button>
        <button
          type="submit"
          className="flex-1 px-4 py-2 bg-gradient-to-r from-yellow-400 to-orange-500 text-white rounded hover:from-yellow-500 hover:to-orange-600 transition-all duration-200 font-medium shadow-md"
        >
          立即送出
        </button>
      </div>
    </form>
  );
} 